#include "Strategy.h"
#include "..\GameLogic\IGrid.h"
#include "..\GameLogic\ICell.h"

CStrategy::CStrategy(IGrid* grid)
	: IStrategy(grid)
{
	m_wolfPosition = CCPointMake(-1,-1);
}

bool CStrategy::CanBeSelected(CCPoint point, int cellType)
{
	if (m_grid->GetCell(point) != NULL)
		return false;
	if (cellType == CELL_TYPE_SHEEP)
	{
		return true;
	}
	else if (cellType == CELL_TYPE_WOLF)
	{
		return CanBeSelectedWolf(point);
	}
	return false;
}

void CStrategy::ApplyRules()
{
}

void CStrategy::ApplyAIMove()
{

}

void CStrategy::ApplyCleanRule( CCPoint point, int cellType )
{
	if (cellType == CELL_TYPE_WOLF)
	{
		CCPoint wolfPos = GetWolfPosition();
		
		if (wolfPos.x >= 0 && wolfPos.y >= 0)
		{
			// clear last wolf
			m_grid->RemoveCell(wolfPos);

			// clean sheep wolf eat
			CCPoint startPos(wolfPos);
			while (!(startPos.x == point.x && startPos.y == point.y))
			{
				ICell* cell = GetCellBetweenByStep(startPos, point, startPos);
				if (startPos.x == point.x && startPos.y == point.y)
					break;
				else if (cell && cell->GetType() == CELL_TYPE_SHEEP)
				{
					m_grid->RemoveCell(startPos);
				}
				else
				{
					assert(1);
				}
			}
		}

		m_wolfPosition = point;
	}
}
bool CStrategy::CanBeSelectedWolf( CCPoint point )
{
	CCPoint wolfPos = GetWolfPosition();
	if (wolfPos.x < 0 && wolfPos.y < 0)
		return true;

	CCPoint startPos(wolfPos);
	int step = 0;
	do
	{
		ICell* cell = GetCellBetweenByStep(startPos, point, startPos);
		if (startPos.x == point.x && startPos.y == point.y)
			return true;
		if (!cell || cell->GetType() != CELL_TYPE_WOLF && cell->GetType() != CELL_TYPE_SHEEP)
			return false;
		step++;
	}while (step < 3);
	return false;
}

ICell* CStrategy::GetCellBetweenByStep(CCPoint from, CCPoint to, CCPoint& posStep)
{
	if (from.x == to.x && from.y == to.y)
		return 0;

	if (from.x == to.x)
	{
		int step = from.y < to.y ? 1 : -1;
		float y = from.y;
		posStep = CCPointMake(from.x, y + step);
		return m_grid->GetCell(posStep);
	}
	else if (from.y == to.y)
	{
		int step = from.x < to.x ? 1 : -1;
		float x = from.x;
		posStep = CCPointMake(x + step, from.y);
		return m_grid->GetCell(posStep);
	}
	return 0;
}

CCPoint CStrategy::GetWolfPosition()
{
	return m_wolfPosition;
}